package com.lym.conf;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.http.HttpServletRequest;

@Configurable
public class CarFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        /*if (request.getMethod().equals("OPTIONS")) {
            return false;
        }*/
        String requestURI = request.getRequestURI();
        if (requestURI.contains("login")){
            return false;
        }
        return true;
    }
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Object run() throws ZuulException {

        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String token = request.getHeader("token");
        String ip = request.getLocalAddr();
        System.out.println(token);

        if(token==null||"".equals(token)){
                //取出白名单的ip
                String ipWhite = (String) redisTemplate.opsForValue().get("whiteIp");
                if(ip.equals(ipWhite)){
                    return null;
                }
                else {
                    return "访问无权限";
                }
            }
            context.setSendZuulResponse(false);
            //设置响应状态码为401-没有权限
            context.setResponseStatusCode(401);
        return null;
    }
}
